-- vim:ts=4:sw=4:et:fdm=marker
-- Standard awesome library
local awful = require("awful")
require("awful.autofocus")
require("awful.rules")
require("beautiful")
local naughty = require("naughty")
--require("test")
local vicious = require("vicious")

-- {{{ Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
    naughty.notify({ preset = naughty.config.presets.critical,
        title = "Oops, there were errors during startup!",
        text = awesome.startup_errors })
end
-- Handle runtime errors after startup
do
    local in_error = false
    awesome.add_signal("debug::error",
        function(err)
            -- Make sure we don't go into an endless error loop
            if in_error then return end
            in_error = true
            naughty.notify({ preset = naughty.config.presets.critical,
                             title = "Oops, an error happened!",
                             text = err })
            in_error = false
        end)
end
-- }}}

-- {{{ Variable definitions
terminal = "urxvt"
editor = "gvim"
dmenu = "dmenu -i -nb '#000000' -nf '#777777' -sb '#770000' -sf '#ffffff' -fn '-*-fixed-medium-r-normal-*-24-*-*-*-*-*-*-*' "
home = os.getenv("HOME")
status_popup = nil
-- }}}

-- {{{ Global functions
-- Shows the tag name + all clients under the tag
function show_all_tags()
    local v = ""
    local tags = screen[mouse.screen]:tags()
    for k, t in ipairs(tags) do
        v = v .. "<span font_desc=\"Verdana Bold 20\">" .. t.name .. "</span>\n"
        for kc, cc in ipairs(t:clients()) do
            v = v .. string.format("%2s: %s\n", kc, tostring(cc.name))
        end
    end
    naughty.notify{ text = v, timeout = 10, margin = 10 }
end

-- Focus the last accessed client independant of tags from the current screen
function client_history_previous_global(idx)
    local counter = 0
    for k, c in ipairs(awful.client.data.focus) do
        if c.screen == mouse.screen then
            if counter == idx then
                for kt, t in ipairs(c:tags()) do
                    awful.tag.viewonly(t)
                    client.focus = c
                    c:raise()
                    return
                end
            end
            counter = counter + 1
        end
    end
end

-- Execute the command once, if cmd is running will not execute again
function run_once(cmd)
    findme = cmd
    firstspace = cmd:find(" ")
    if firstspace then
        findme = cmd:sub(0, firstspace-1)
    end
    awful.util.spawn_with_shell("pgrep -u $USER -x " .. findme .. " > /dev/null || (" .. cmd .. ")")
end

function dmenu_prompt(file, prompt, col)
    local cmd
    local awk = ""
    if col ~= 0 then awk = " | awk '{print $" .. col .. "}'" end
    if file ~= "" then
        cmd = "cat '" .. file .. "' | " .. dmenu .. "-l 10 -p '" .. prompt .. "'" .. awk
    else
        cmd = "echo | " .. dmenu .. "-b -p '" .. prompt .. "'" .. awk
    end
    --naughty.notify({ title = "Exec", text = cmd, timeout = 10 })
    return awful.util.pread(cmd):gsub("\n$", "")
end

function awful_prompt(txt, cb, hist)
    local s = mouse.screen
    --mywibox2[s].visible = true
    awful.prompt.run({ prompt = "<span color='#ffff00'>" .. txt .. "</span>" },
        mypromptbox[s].widget, cb, nil,
        awful.util.getdir("cache") .. "/history_" .. hist, 10,
        function()
            --mywibox2[s].visible = false
        end)
end
-- }}}

-- {{{ Customization
beautiful.init(home .. "/.config/awesome/theme.lua")

-- {{{ Naughty customization
naughty.config.default_preset.font             = "Inconsolata Medium 18"
naughty.config.default_preset.position         = "bottom_left"
naughty.config.default_preset.timeout          = 5
-- }}}

modkey = "Mod4"
altkey = "Mod1"

-- Table of layouts to cover with awful.layout.inc, order matters.
layouts =
{
    awful.layout.suit.max,
    awful.layout.suit.tile,
    awful.layout.suit.tile.bottom,
    awful.layout.suit.floating,
    awful.layout.suit.max.fullscreen,
}
-- }}}

-- {{{ Tags
-- Define a tag table which hold all screen tags.
-- NOTE tags table is unused
tags = {}
for s = 1, screen.count() do
    -- Each screen has its own tag table.
    tags[s] = awful.tag({ "[main]", "[junk]" }, s, layouts[1])
end
-- }}}

-- {{{ Menu
-- Create a laucher widget and a main menu
myawesomemenu = {
   { "manual", terminal .. " -e man awesome" },
   { "edit config", editor .. " " .. awesome.conffile },
   { "restart", awesome.restart },
   { "quit", awesome.quit }
}
mymainmenu = awful.menu({ items = { { "awesome", myawesomemenu, beautiful.awesome_icon },
                                    { "open terminal", terminal }
                                  }
                        })
-- }}}

-- {{{ Wibox
-- Separator
sepwidget = widget({ type = "textbox" })
sepwidget.text = "<span color='#666666'>|</span>"

-- Volume
volwidget = widget({ type = "textbox" })
vicious.register(volwidget, vicious.widgets.volume, "<span color='#ffffff'>♬ $1</span>", 1, "Master")

-- Battery
batwidget = widget({ type = "textbox" })
vicious.register(batwidget, vicious.widgets.bat,
    function(widget, args)
        local col = '#ffffff'
        if args[2] < 20 then col = '#ffff00' end
        return "<span color='" .. col .. "'>⏚ " .. args[2] .. args[1] .. "</span>"
    end, 5, "BAT1")

-- CPU
cpuwidget = widget({ type = "textbox" })
vicious.register(cpuwidget, vicious.widgets.cpu,
    function(widget, args)
        return string.format("<span color='#ffffff'>⚡ %2d", args[1]) .. '%</span>'
    end, 1)
--cputxtwidget = widget({ type = "textbox" })
--cputxtwidget.text = "<span color='#ffffff'>⚡ </span>"
--cpuwidget = awful.widget.progressbar()
--cpuwidget:set_width(16)
--cpuwidget:set_height(30)
--cpuwidget:set_vertical(true)
--cpuwidget:set_background_color("#494B4F")
--cpuwidget:set_border_color(nil)
--cpuwidget:set_color("#000000")
--cpuwidget:set_gradient_colors({ "#330000", "#777777", "#FF0000" })
--cpuwidget_t = awful.tooltip({ objects = { cpuwidget.widget },})
--vicious.register(cpuwidget, vicious.widgets.cpu,
    --function (widget, args)
        --cpuwidget_t:set_text("CPU Usage: " .. args[1] .. "%")
        --return args[1]
    --end, 5)

-- Mem
memwidget = widget({ type = "textbox" })
vicious.register(memwidget, vicious.widgets.mem,
    function(widget, args)
        return string.format("<span color='#ffffff'>⎚ %2d", args[1]) .. '%</span>'
    end, 1)
--memtxtwidget = widget({ type = "textbox" })
--memtxtwidget.text = "<span color='#ffffff'>⎚ </span>"
--memwidget = awful.widget.progressbar()
--memwidget:set_width(16)
--memwidget:set_height(30)
--memwidget:set_vertical(true)
--memwidget:set_background_color("#494B4F")
--memwidget:set_border_color(nil)
--memwidget:set_color("#000000")
--memwidget:set_gradient_colors({ "#330000", "#777777", "#FF0000" })
--memwidget_t = awful.tooltip({ objects = { memwidget.widget },})
--vicious.register(memwidget, vicious.widgets.mem,
    --function (widget, args)
        --memwidget_t:set_text(" RAM: " .. args[2] .. "MB / " .. args[3] .. "MB (" .. args[1] .. "%)")
        --return args[1]
    --end, 5)

-- Updates
updwidget = widget({ type = "textbox" })
vicious.register(updwidget, vicious.widgets.pkg, "<span color='#ffffff'>⌘ $1</span>", 1801, "Ubuntu")

-- Layout
keywidget = widget({ type = 'textbox' })
keywidget.text = "<span color='#ffffff'>⌨ dv</span>"

-- Date
datewidget = widget({ type = "textbox" })
vicious.register(datewidget, vicious.widgets.date, "<span color='orange'>%w %m/%d %I:%M %p</span> ", 60)
--datewidget_t = awful.tooltip({
    --objects = { datewidget },
    --timer_function = function() return os.date("%a %m/%d/%Y\n%I:%M %p") end })

-- Create a systray
mysystray = widget({ type = "systray" })

-- Create a wibox for each screen and add it
mymousefinder = awful.mouse.finder()
mywibox = {}
--mywibox2 = {}
mypromptbox = {}
--mylayoutbox = {}
mytaglist = {}
--mytaglist.buttons = awful.util.table.join(
    --awful.button({ }, 1, awful.tag.viewonly),
    --awful.button({ modkey }, 1, awful.client.movetotag),
    --awful.button({ }, 3, awful.tag.viewtoggle),
    --awful.button({ modkey }, 3, awful.client.toggletag),
    --awful.button({ }, 4, awful.tag.viewnext),
    --awful.button({ }, 5, awful.tag.viewprev)
--)
mytasklist = {}
mytasklist.buttons = awful.util.table.join(
    awful.button({ }, 1,
        function(c)
            if c == client.focus then
                c.minimized = true
            else
                if not c:isvisible() then
                    awful.tag.viewonly(c:tags()[1])
                end
                -- This will also un-minimize
                -- the client, if needed
                client.focus = c
            end
        end))

for s = 1, screen.count() do
    -- Create a promptbox for each screen
    mypromptbox[s] = awful.widget.prompt({ })
    -- Create an imagebox widget which will contains an icon indicating which layout we're using.
    -- We need one layoutbox per screen.
    --mylayoutbox[s] = awful.widget.layoutbox(s)
    --mylayoutbox[s]:buttons(awful.util.table.join(
                           --awful.button({ }, 1, function() awful.layout.inc(layouts, 1) end),
                           --awful.button({ }, 3, function() awful.layout.inc(layouts, -1) end)))
    -- Create a taglist widget, only shows currently selected tag
    mytaglist[s] = awful.widget.taglist(s, function(t, args)
        if t.selected then
            return awful.widget.taglist.label.all(t, args)
        end
    end, mytaglist.buttons)

    -- Create a tasklist widget, remove the icon
    mytasklist[s] = awful.widget.tasklist(function(c)
        local text, bg, status_image, icon = awful.widget.tasklist.label.currenttags(c, s)
        return text, bg, status_image
        --return awful.widget.tasklist.label.currenttags(c, s)
    end, mytasklist.buttons)

    -- Create the wibox
    --mywibox2[s] = awful.wibox({ position = "top", screen = s, fg = "#ffffff", hidden = true })
    --mywibox2[s].visible = false
    --mywibox2[s].widgets = {
        --{
            --mypromptbox[s],
            --layout = awful.widget.layout.horizontal.leftright
        --}}

    mywibox[s] = awful.wibox({ position = "bottom", screen = s })
    -- Add widgets to the wibox - order matters
    mywibox[s].widgets = {
        {
            mytaglist[s],
            mypromptbox[s],
            layout = awful.widget.layout.horizontal.leftright
        },
        s == 1 and mysystray or nil,
        --mylayoutbox[s],
        datewidget,
        sepwidget,
        keywidget,
        sepwidget,
        updwidget,
        sepwidget,
        memwidget,
        sepwidget,
        cpuwidget,
        sepwidget,
        batwidget,
        sepwidget,
        volwidget,
        sepwidget,
        mytasklist[s],
        layout = awful.widget.layout.horizontal.rightleft
    }
end
-- }}}

-- {{{ Mouse bindings
--root.buttons(awful.util.table.join(
    --awful.button({ }, 3, function() mymainmenu:toggle() end),
    --awful.button({ }, 4, awful.tag.viewnext),
    --awful.button({ }, 5, awful.tag.viewprev)
--))
-- }}}

-- {{{ Key bindings
globalkeys = awful.util.table.join(
    -- {{{ Client operations
    awful.key({ modkey,           }, "Left",   awful.tag.viewprev       ),
    awful.key({ modkey,           }, "Right",  awful.tag.viewnext       ),
    awful.key({ modkey,           }, "comma",   awful.tag.viewprev       ),
    awful.key({ modkey,           }, "period",  awful.tag.viewnext       ),
    awful.key({ modkey,           }, "Tab", awful.tag.history.restore),
    awful.key({ modkey,           }, "Escape", function() client_history_previous_global(1) end),
    awful.key({ modkey,           }, "n",
        function()
            awful.client.focus.byidx( 1)
            if client.focus then client.focus:raise() end
        end),
    awful.key({ modkey,           }, "p",
        function()
            awful.client.focus.byidx(-1)
            if client.focus then client.focus:raise() end
        end),
    awful.key({ altkey,           }, "Tab",
        function()
            awful.client.focus.byidx( 1)
            if client.focus then client.focus:raise() end
        end),
    awful.key({ altkey, "Shift"   }, "Tab",
        function()
            awful.client.focus.byidx(-1)
            if client.focus then client.focus:raise() end
        end),
    awful.key({ modkey,           }, "u", function() awful.client.urgent.jumpto() end),
    awful.key({ modkey, "Shift"   }, "i", awful.client.restore),
    awful.key({ modkey,           }, "w", function() mymainmenu:show({keygrabber=true}) end),
    -- }}}

    -- {{{ Layout manipulation
    awful.key({ modkey,           }, "l",     function() awful.tag.incmwfact( 0.05)    end),
    awful.key({ modkey,           }, "h",     function() awful.tag.incmwfact(-0.05)    end),
    awful.key({ modkey, "Shift"   }, "h",     function() awful.tag.incnmaster( 1)      end),
    awful.key({ modkey, "Shift"   }, "l",     function() awful.tag.incnmaster(-1)      end),
    awful.key({ modkey, "Control" }, "h",     function() awful.tag.incncol( 1)         end),
    awful.key({ modkey, "Control" }, "l",     function() awful.tag.incncol(-1)         end),
    awful.key({ modkey,           }, "space", function() awful.layout.inc(layouts,  1) end),
    awful.key({ modkey, "Shift"   }, "space", function() awful.layout.inc(layouts, -1) end),
    awful.key({ modkey, "Shift"   }, "n", function() awful.client.swap.byidx(  1)    end),
    awful.key({ modkey, "Shift"   }, "p", function() awful.client.swap.byidx( -1)    end),
    --awful.key({ modkey, "Control" }, "n", function() awful.screen.focus_relative( 1) end),
    --awful.key({ modkey, "Control" }, "p", function() awful.screen.focus_relative(-1) end),
    -- }}}

    -- {{{ Awesome controls
    awful.key({ modkey, "Control" }, "r", awesome.restart),
    awful.key({ modkey, "Control" }, "q", awesome.quit),
    awful.key({ modkey }, "b", function() mywibox[mouse.screen].visible = not mywibox[mouse.screen].visible end),
    awful.key({ modkey }, "'", function() mymousefinder:find() end ),
    awful.key({ modkey }, "s", function() mymousefinder:find() end ),
    awful.key({ modkey }, "a",
        function()
            if status_popup ~= nil then
                naughty.destroy(status_popup)
                status_popup = nil
            else
                r = os.date("<span font_desc='Verdana Bold 20'>Date</span>\n<span color='#ffffff'>%a %m-%d-%Y %I:%M %p</span>\n")
                r = r .. "<span font_desc='Verdana Bold 20'>Battery</span>\n<span color='#ffffff'>" .. batwidget.text .. "</span>\n"
                r = r .. "<span font_desc='Verdana Bold 20'>Volume</span>\n<span color='#ffffff'>" .. volwidget.text .. "</span>\n"
                r = r .. "<span font_desc='Verdana Bold 20'>CPU</span>\n<span color='#ffffff'>" .. cpuwidget.text .. "</span>\n"
                r = r .. "<span font_desc='Verdana Bold 20'>Memory</span>\n<span color='#ffffff'>" .. memwidget.text .. "</span>\n"
                r = r .. "<span font_desc='Verdana Bold 20'>Updates</span>\n<span color='#ffffff'>" .. updwidget.text .. "</span>\n"
                r = r .. "<span font_desc='Verdana Bold 20'>Keyboard</span>\n<span color='#ffffff'>" .. keywidget.text .. "</span>\n"
                r = r .. "<span font_desc='Verdana Bold 20'>Layout</span>\n<span color='#ffffff'>" .. awful.layout.getname(awful.layout.get(mouse.screen)) .. "</span>"
                -- TODO add more data
                status_popup = naughty.notify({ text = r, timeout = 5, hover_timeout = 1 })
            end
        end),
    -- }}}

    -- {{{ Applications
    awful.key({ modkey, "Shift" }, "Return", function() awful.util.spawn(terminal) end),
    awful.key({ modkey, "Shift" }, "v", function() awful.util.spawn(editor) end),
    awful.key({ modkey, "Shift" }, "f", function() awful.util.spawn("google-chrome") end),
    awful.key({ modkey, "Control", "Shift" }, "f", function() awful.util.spawn("google-chrome --user-data-dir=" .. home .. "/.config/google-chrome/testing") end),
    awful.key({ modkey, altkey, "Shift" }, "f", function() awful.util.spawn("google-chrome --user-data-dir=" .. home .. "/.config/google-chrome/work") end),
    awful.key({ modkey }, "Home",
        function()
            keywidget.text = "<span color='#ffffff'>⌨ us</span>"
            os.execute("setxkbmap us -option")
        end),
    awful.key({ modkey }, "End",
        function()
            keywidget.text = "<span color='#ffffff'>⌨ dv</span>"
            os.execute("setxkbmap dvorak -option caps:swapescape -option compose:ralt")
        end),
    awful.key({ modkey, "Control", "Shift" }, "p",
        function()
            local sel = awful.util.pread("xsel -ob"):gsub("\n$", "")
            awful.util.spawn(home .. "/code/dev/bpass/bpass.sh " .. home .. "/code/dev/bpass/config.txt '" .. sel .. "'")
        end),
    awful.key({ modkey, "Control", "Shift" }, "l", function() awful.util.spawn("xscreensaver-command -lock") end),
    awful.key({ modkey }, "Scroll_Lock", function() awful.util.spawn("xscreensaver-command -lock") end),
    awful.key({ modkey, "Control" }, "End", function() os.execute("sleep 1 && xset dpms force off") end),
    -- }}}

    -- {{{ MPD
    awful.key({ modkey }, "e",
             function()
                local command = dmenu_prompt(home .. "/.ratpoison/stations", "> ", 2)
                if command == "" then return end
                os.execute(home .. "/.ratpoison/mpd_handler " .. command)
             end),
    awful.key({ modkey },            "m",
        function()
             keygrabber.run(function(mod, key, event)
                 if event == "release" then return true end
                 keygrabber.stop()
                 if key == "c" then os.execute("mpc current -f '[[%artist% - ]%title%]' | xsel -ibp")
                 elseif key == "e" then
                     local r = awful.util.pread("mpc current -f '[[%artist% - ]%title%]'"):gsub("\n$", "")
                     if r == "" then return end
                     naughty.notify({ title = "MPC Current", text = r, timeout = 5, hover_timeout = 1 })
                 elseif key == "r" then os.execute("mpc play")
                 elseif key == "s" then os.execute("mpc stop")
                 elseif key == "l" then os.execute("mpc clear")
                 else naughty.notify({ text = "<span color='#ffffff'>Unknown key: " .. key .. "</span>", timeout = 1 })
                 end
                 return true
             end)
        end),
    -- }}}

    -- {{{ Volume
    awful.key({ modkey }, "Next", function() os.execute("amixer -c0 sset Master 5%- >/dev/null") end),
    awful.key({ modkey }, "Prior", function() os.execute("amixer -c0 sset Master 5%+ >/dev/null") end),
    awful.key({ modkey },            "v",
        function()
             keygrabber.run(function(mod, key, event)
                 if event == "release" then return true end
                 keygrabber.stop()
                 if key == "`" then os.execute("amixer sset Master 0")
                 elseif key == "1" then os.execute("amixer sset Master 10")
                 elseif key == "2" then os.execute("amixer sset Master 20")
                 elseif key == "3" then os.execute("amixer sset Master 30")
                 elseif key == "4" then os.execute("amixer sset Master 40")
                 elseif key == "5" then os.execute("amixer sset Master 50")
                 elseif key == "6" then os.execute("amixer sset Master 60")
                 elseif key == "7" then os.execute("amixer sset Master 70")
                 elseif key == "8" then os.execute("amixer sset Master 80")
                 elseif key == "9" then os.execute("amixer sset Master 90")
                 elseif key == "0" then os.execute("amixer sset Master 100")
                 elseif key == "Up" then os.execute("amixer -c0 sset Master 5%+ >/dev/null")
                 elseif key == "Down" then os.execute("amixer -c0 sset Master 5%- >/dev/null")
                 elseif key == "m" then os.execute(home .. "/.i3/mute.sh")
                 elseif key == "v" then os.execute(home .. "/.i3/mute.sh")
                 else naughty.notify({ text = "<span color='#ffffff'>Unknown key: " .. key .. "</span>", timeout = 1 })
                 end
                 return true
             end)
        end),
    -- }}}

    -- {{{ Prompts
    awful.key({ }, "Print",
        function()
            --local file = dmenu_prompt('', 'file> ', 0)
            --if file == "" then return end
            --awful.util.spawn("import " .. home .. "/" .. file)
            awful_prompt("Screenshot file: ",
                function(file)
                    awful.util.spawn("import " .. home .. "/" .. file)
                end, "screenshot")
        end),
    awful.key({ modkey }, "r",
        function()
            --mypromptbox[mouse.screen]:run()
            awful_prompt("Run: ", awful.util.spawn, "run")
        end),
    awful.key({ modkey }, "F11",
        function()
            --local expr = dmenu_prompt('', 'calc> ', 0)
            --if expr == "" then return end
            --local result = awful.util.pread("perl -I " .. home .. "/code " .. home .. "/bin/calc.pl -q '" .. expr .. "' 2>&1", 'r'):gsub("\n$", "")
            --naughty.notify({ title = "Calc result", text = expr .. " = " .. result, timeout = 10 })
            awful_prompt("Calc: ",
                function(expr)
                    local result = awful.util.pread("perl -I " .. home .. "/code " .. home .. "/bin/calc.pl -q '" .. expr .. "' 2>&1", 'r'):gsub("\n$", "")
                    naughty.notify({ title = "Calc result", text = "<span color='#ffffff'>" .. expr .. " = " .. result .. "</span>", timeout = 10, hover_timeout = 1 })
                end, "calc")
        end),
    awful.key({ modkey }, "x", function() awful_prompt("Run Lua code: ", awful.util.eval, "history") end),
    --awful.key({ modkey }, "`", function() test.do_command(mywibox2, mypromptbox, "cmd") end),
    -- }}}

    -- {{{ Dynamic tags
    awful.key({ modkey, "Shift" }, "a",
        function()
            awful_prompt("Tag: ",
                function(name)
                    local s = mouse.screen
                    name = '[' .. name .. ']'
                    props = {selected = true, layout = layouts[1]}
                    t = awful.tag.add(name, props)
                    awful.tag.viewonly(t)
                end, "tag")
            --local name = dmenu_prompt('', 'tag> ', 0)
            --if name == "" then return end
            --local s = mouse.screen
            --name = '[' .. name .. ']'
            --props = {selected = true, layout = layouts[1]}
            --t = awful.tag.add(name, props)
            --awful.tag.viewonly(t)
        end),
    awful.key({ modkey, "Shift" }, "d", function() awful.tag.delete() end),
    awful.key({ modkey, "Shift" }, "r",
        function()
            awful_prompt("Rename tag: ",
                function(name)
                    local s = mouse.screen
                    local tag = awful.tag.selected(s)
                    if tag then tag.name = "[" .. name .. "]" end
                end, "tag")
        end)
    -- }}}
)

-- Window selection
for i = 1, 9 do
    globalkeys = awful.util.table.join(globalkeys,
    awful.key({ modkey,           }, i,
        function()
            local v = awful.client.visible()
            if i <= #v then
                client.focus = v[i]
                if client.focus then client.focus:raise() end
            end
        end))
end

-- Focus workspace
for i = 1, 9 do
    globalkeys = awful.util.table.join(globalkeys,
        awful.key({ modkey }, "F" .. i,
                  function()
                      local tag = screen[mouse.screen]:tags()[i]
                      if tag then awful.tag.viewonly(tag) end
                  end),
        awful.key({ modkey, "Control", "Shift" }, "F" .. i,
                  function()
                      local tag = screen[mouse.screen]:tags()[i]
                      if tag then awful.tag.viewtoggle(tag) end
                  end),
        awful.key({ modkey, "Shift" }, "F" .. i,
                  function()
                      local tag = screen[mouse.screen]:tags()[i]
                      if client.focus and tag then awful.client.movetotag(tag) end
                  end),
        awful.key({ modkey, "Control" }, "F" .. i,
                  function()
                      local tag = screen[mouse.screen]:tags()[i]
                      if client.focus and tag then awful.client.toggletag(tag) end
                  end))
end

-- Client keys
clientkeys = awful.util.table.join(
    awful.key({ modkey,           }, "f",       function(c) c.fullscreen = not c.fullscreen end),
    awful.key({ modkey, "Shift"   }, "c",       function(c) os.execute("kill -9 " .. c.pid) end),
    awful.key({ altkey,           }, "F4",      function(c) c:kill() end),
    awful.key({ modkey, "Control" }, "space",   awful.client.floating.toggle ),
    awful.key({ modkey,           }, "Return",  function(c) c:swap(awful.client.getmaster()) end),
    --awful.key({ modkey, "Shift"   }, "r",       function(c) c:redraw() end),
    awful.key({ modkey,           }, "i",       function(c) c.minimized = true end),
    --awful.key({ modkey,           }, "o",       awful.client.movetoscreen                        ),
    --awful.key({ modkey,           }, "t",       function(c) c.ontop = not c.ontop end),
    awful.key({ modkey, "Shift"   }, "comma",
        function (c)
            local tags = screen[mouse.screen]:tags()
            local curidx = awful.tag.getidx(c:tags()[1])
            if curidx == 1 then
                c:tags({tags[#tags]})
            else
                c:tags({tags[curidx - 1]})
            end
        end),
    awful.key({ modkey, "Shift"   }, "period",
      function (c)
            local tags = screen[mouse.screen]:tags()
            local curidx = awful.tag.getidx(c:tags()[1])
            if curidx == #tags then
                c:tags({tags[1]})
            else
                c:tags({tags[curidx + 1]})
            end
        end)
)

-- Mouse controls for clients
clientbuttons = awful.util.table.join(
    awful.button({ }, 1, function(c) client.focus = c end),
    awful.button({ modkey }, 1, awful.mouse.client.move),
    awful.button({ modkey }, 3, awful.mouse.client.resize))

-- Set keys
root.keys(globalkeys)
-- }}}

-- {{{ Rules
awful.rules.rules = {
    -- All clients will match this rule.
    { rule = { },
        properties = { border_width = beautiful.border_width,
                border_color = beautiful.border_normal,
                focus = true,
                keys = clientkeys,
                buttons = clientbuttons } },
    -- Make mplayer float
    { rule = { class = "MPlayer" },
        properties = { floating = true } },
    { rule = { class = "Exe"},
        properties = {floating = true} },
    -- Gvim needs be scaled to not allow the lower window to bleed
    { rule = { class = "Gvim" },
        properties = { size_hints_honor = false } },
    { rule = { class = "URxvt" },
        properties = { size_hints_honor = false } },
}
-- }}}

-- {{{ Signals
-- Signal for when focused, auto-raise clients when focused
client.add_signal("focus", function(c)
    c.border_color = beautiful.border_focus
    c:raise()
end)

client.add_signal("unfocus", function(c)
    c.border_color = beautiful.border_normal
end)

-- Signal function to execute when a new client appears.
client.add_signal("manage", function(c, startup)
    -- Add a titlebar
    -- awful.titlebar.add(c, { modkey = modkey })

    if not startup then
        -- Set the windows at the slave,
        -- i.e. put it at the end of others instead of setting it master.
        awful.client.setslave(c)

        -- Put windows in a smart way, only if they does not set an initial position.
        if not c.size_hints.user_position and not c.size_hints.program_position then
            awful.placement.no_overlap(c)
            awful.placement.no_offscreen(c)
        end
    end
end)

-- Launch apps once
run_once(home .. "/bin/img.sh")
run_once("synclient TapButton1=0 TapButton2=0 TapButton3=0 MinSpeed=1.5 MaxSpeed=3.0 AccelFactor=0.1")
run_once("xscreensaver -no-splash")
run_once("nm-applet --sm-disable")
--Moved to .profile
--run_once("setxkbmap dvorak -option caps:swapescape -option compose:menu")

-- }}}
